package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.DishDto;
import com.itheima.pojo.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishDtoService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishDtoService dishDtoService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/page")
    public R page(Integer page,Integer pageSize,String name){


        Page page1=new Page(page,pageSize);
        LambdaQueryWrapper<Dish> wrapper=new LambdaQueryWrapper<>();
        wrapper.like(name!=null,Dish::getName,name);
        dishService.page(page1,wrapper);
        List<Dish> records = page1.getRecords();
        List<DishDto> dishDtoList=new ArrayList<>();
        Page page2=new Page();
        BeanUtils.copyProperties(page1,page2,"records");

        for (Dish record : records) {
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(record,dishDto);
            Long categoryId = record.getCategoryId();
            Category category = categoryService.getById(categoryId);
            dishDto.setCategoryName(category.getName());
            dishDtoList.add(dishDto);
        }
        page2.setRecords(dishDtoList);



        return R.success(page2);
    }

@PostMapping
    public R addDish(@RequestBody DishDto dishDto){
    Set keys = redisTemplate.keys("dish_*");
    redisTemplate.delete(keys);

        dishService.add(dishDto);
        return R.success("添加成功！");
    }

@GetMapping("/{id}")
    public R getDishById(@PathVariable Long id){

    Dish dish = dishService.getById(id);
    LambdaQueryWrapper<DishFlavor> wrapper=new LambdaQueryWrapper<>();
    wrapper.eq(id!=null,DishFlavor::getDishId,id);
    List<DishFlavor> list = dishFlavorService.list(wrapper);
    DishDto dishDto=new DishDto();
    BeanUtils.copyProperties(dish,dishDto);
    dishDto.setFlavors(list);
    return R.success(dishDto);


}

@PutMapping
public R update(@RequestBody DishDto dishDto){
    Set keys = redisTemplate.keys("dish_*");
    redisTemplate.delete(keys);
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDto,dish);
        dishService.updateById(dish);
    List<DishFlavor> flavors = dishDto.getFlavors();
    List<DishFlavor> list=new ArrayList<>();
    Long dishId = dishDto.getId();
    for (DishFlavor flavor : flavors) {
        DishFlavor dishFlavor=new DishFlavor();
//        Long dishId = flavor.getDishId();
//        LambdaQueryWrapper<DishFlavor> wrapper=new LambdaQueryWrapper<>();
//        wrapper.eq(DishFlavor::getDishId,dishId);
//        Long dishId = flavor.getDishId();
        String name = flavor.getName();
        String value = flavor.getValue();
        dishFlavor.setDishId(dishId);
        dishFlavor.setName(name);
        dishFlavor.setValue(value);
        list.add(dishFlavor);
    }
    LambdaQueryWrapper<DishFlavor> wrapper=new LambdaQueryWrapper<>();
    wrapper.eq(DishFlavor::getDishId,dishId);
    dishFlavorService.remove(wrapper);

        dishFlavorService.saveBatch(list);


    return R.success("修改成功！");

}
@DeleteMapping
public R delete(@RequestParam("ids") List<Long> ids){
    Set keys = redisTemplate.keys("dish_*");
    redisTemplate.delete(keys);
    List<Dish> dishes = dishService.listByIds(ids);
    long count1 = dishes.stream().count();
    int count=0;


    for (Dish dish : dishes) {
        Integer status = dish.getStatus();
        if (status==0){
            count+=1;
            Long id = dish.getId();
            LambdaQueryWrapper<DishFlavor> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(DishFlavor::getDishId,id);
            dishFlavorService.remove(wrapper);
            dishService.removeById(dish.getId());
        }
    }

    if (count!=count1){
        return R.error("所选的对象为启售状态，不能删除！");
    }



//    for (Long id : ids) {
//
//        LambdaQueryWrapper<DishFlavor> wrapper=new LambdaQueryWrapper<>();
//        wrapper.eq(DishFlavor::getDishId,id);
//       dishFlavorService.remove(wrapper);
//    }
//        dishService.removeByIds(ids);

        return R.success("删除成功！");


}

@PostMapping("/status/{status}")
public R updateStatus(@PathVariable Integer status,@RequestParam("ids") List<Long> ids){
    Set keys = redisTemplate.keys("dish_*");
    redisTemplate.delete(keys);

    for (Long id : ids) {

        Dish dish = dishService.getById(id);
        dish.setStatus(status);
        dishService.updateById(dish);

    }

    return R.success("修改成功！");

}
@GetMapping("/list")
public R list(Long categoryId,Integer status){
        String dishkey="dish_"+categoryId+"_"+status;

    List<DishDto>  dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(dishkey);

    if (dishDtos!=null){

        return R.success(dishDtos);
    }


    LambdaQueryWrapper<Dish> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId,categoryId);
    List<Dish> dishList = dishService.list(wrapper);
     dishDtos =new ArrayList<>();

    for (Dish dish : dishList) {
        DishDto dishDto = new DishDto();
        //1.把dish的属性值copy给dishDto
        BeanUtils.copyProperties(dish,dishDto);
        //2.查询菜品的口味数据
        // select * from dish_flavor where dish_id = ?
        LambdaUpdateWrapper<DishFlavor> qw1 = new LambdaUpdateWrapper<>();
        qw1.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(qw1);
        //3.将菜品的口味列表 set给 dishDto
        dishDto.setFlavors(flavors);
        //4.将dishDto放入到 dishDtos 集合中
        dishDtos.add(dishDto);

    }

    redisTemplate.opsForValue().set(dishkey,dishDtos);


    return R.success(dishDtos);
    }
}
